import cloud from '@lafjs/cloud'
import { setUserInfo } from "@/thirdParty/moxueyuanUtils";
const db = cloud.mongo.db

export async function changeStudentSource(out_trade_no) {
  //获取 课程 id
  let { curriculum_id, status, userId, approvalContent } = await cloud.nw.db.findByWhereJson({
    dbName: "web-order",
    whereJson: { out_trade_no },
  });

  //获取课程里面的用户来源/课程标签
  let { studentSource } = await cloud.nw.db.findByWhereJson({
    dbName: "web-course",
    whereJson: { _id: curriculum_id },
  });

  //抓取出标签
  let tags = <any>[]
  if (approvalContent.selectLesson && approvalContent.selectLesson.length) {
    approvalContent.selectLesson.forEach(element => {
      if (element.tag) tags.push(element.tag)
    });
  }


  //如果订单状态是报名成功，则去魔学院创建用户
  if (status == 2) {
    let resp = await cloud.nw.db.findByWhereJson({
      dbName: "moxueyuan-user-detail",
      whereJson: { userid: userId },
    });
    console.log("魔学院的用户信息", resp)

    let tagArr = <any>[]
    if (resp && resp._id) {
      let { tag } = resp
      tagArr = [...tag, ...tags]
    } else {
      tagArr = [...tags]
    }
    let obj = { ...approvalContent.model, userId, tag: cloud.utils.unique(tagArr) }
    setUserInfo(obj);
  } else if (status == 4) { //如果是退款，则删除用户的来源
    //获取该用户所有报名成功/开票的订单标签
    let allTags = <any>[]
    const docs = await db.collection('web-order').find({ status: { $in: [2, 7] }, userId }).toArray()

    docs.forEach(element => {
      let selectLesson = [...element.approvalContent.selectLesson]
      selectLesson.forEach(item => {
        allTags.push(item.tag)
      });
    });

    console.log("最终标签", cloud.utils.unique(allTags))
    let obj = { ...approvalContent.model, userId, tag: cloud.utils.unique(allTags) }
    setUserInfo(obj);
  }


  //获取用户信息
  let res = await cloud.nw.db.findByWhereJson({
    dbName: "web-users",
    whereJson: { _id: userId },
  });

  //获取用户的来源列表
  let arr = res.studentSourceList || [];
  console.log("原本用户的来源列表", arr, studentSource)

  //如果是报名成功和已开票状态，则添加用户的来源
  if ([2, 7].includes(status)) {
    //判断该用户当前的学员来源里面是否有该条来源
    if (!cloud.utils.isFieldEqual(arr, "source", studentSource)) {
      arr.push({ source: studentSource, curriculumId: curriculum_id })
    }
  } else if (status == 4) { //如果是退款，则删除用户的来源
    let index = cloud.utils.findIndexByField(arr, "source", studentSource)
    if (index != -1) arr.splice(index, 1)
  }
  console.log("更新后的用户来源列表", arr)
  await cloud.nw.db.update({
    dbName: "web-users",
    whereJson: { _id: userId },
    dataJson: { studentSourceList: arr }
  });

  return cloud.utils.requestReturn({ data: "" });
}
